package cn.rengy.tpa.wxmp.wxapp.code;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;

import com.alibaba.fastjson.JSONObject;

import cn.rengy.tpa.wxmp.exception.WeChatException;
import cn.rengy.tpa.wxmp.token.AccessToken;
import cn.rengy.tpa.wxmp.util.WeChatReturnCode;
import cn.rengy.tpa.wxmp.util.WeChatUtil;

public class ACodeApi {
	private static Logger logger = LoggerFactory.getLogger(ACodeApi.class);

	private static final String GETWXACODEUNLIMITURL="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
	private static final MediaType MEDIA_TYPE_IMAGE=MediaType.valueOf("image/*");
	public static File getwxacodeunlimit(AccessToken accessToken,GetwxacodeunlimitRequest getwxacodeunlimitRequest,File targetDirectory) throws ClientProtocolException, IOException {
		for(int i=0;i<2;i++) {
			Request request = Request.Post(GETWXACODEUNLIMITURL+accessToken.token())
					.bodyString(JSONObject.toJSONString(getwxacodeunlimitRequest),ContentType.APPLICATION_JSON);
			HttpResponse httpResponse = request.execute().returnResponse();
			HttpEntity httpEntity=httpResponse.getEntity();
			String contentType=httpEntity.getContentType().getValue();
			MediaType mediaType=MediaType.valueOf(contentType);
			if(MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)||MediaType.TEXT_PLAIN.isCompatibleWith(mediaType)) {
				String jsonString=EntityUtils.toString(httpEntity,Consts.UTF_8);
				JSONObject resultObject=JSONObject.parseObject(jsonString);
				int errCode =resultObject.getIntValue("errcode");
				if(WeChatUtil.isAccessTokenInvalid(errCode)){
					accessToken.refresh();
				}else{
					String errMsg = WeChatReturnCode.getMsg(errCode,resultObject.getString("errmsg"));
					throw new WeChatException(errCode,errMsg);
				}
			}else if(MEDIA_TYPE_IMAGE.includes(mediaType)){
				String newFileName=null;
				Header header=httpResponse.getFirstHeader("Content-disposition");
				if(header!=null){
					HeaderElement headerElement=header.getElements()[0];
					String fileName=headerElement.getParameterByName("filename").getValue();
					newFileName=UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(fileName);
				}else {
					//解析后缀
					throw new WeChatException("Content-disposition为空");
				}
				File targetFile = new File(targetDirectory ,newFileName);
				FileCopyUtils.copy(httpEntity.getContent(), new FileOutputStream(targetFile));
				return targetFile;
			}else {
				logger.error(mediaType.toString());
			}
		}
		return null;
	}
}
